package com.gzhryc.html;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import com.gzhryc.common.logging.Logger;
import com.gzhryc.html.models.HtmlTemplate;
import com.gzhryc.html.models.HtmlTheme;
import com.gzhryc.servlet.Resource;
import com.gzhryc.servlet.resources.VelocityResource;

public class HtmlResource extends Resource{
	
	private final static Logger log = Logger.getLogger(HtmlResource.class);
	
	private String prefixPath;
	private String htmlTheme;
	private String htmlPath;
	
	public HtmlResource(String htmlTheme) {
		this.htmlTheme = htmlTheme;
	}
	
	public HtmlResource(String htmlTheme,String htmlPath) {
		this.htmlTheme = htmlTheme;
		this.htmlPath = htmlPath;
	}
	
	public HtmlResource(String htmlTheme,String prefixPath,String htmlPath) {
		this.htmlTheme = htmlTheme;
		this.prefixPath = prefixPath;
		this.htmlPath = htmlPath;
	}

	@Override
	public void export(HttpServletRequest request, HttpServletResponse response) throws Exception {
		if(StringUtils.isNotBlank(htmlTheme)) {
			HtmlTheme htmlThemeEntity = HtmlThemeManager.self().getByCode(htmlTheme);
			if(htmlThemeEntity != null) {
				if(StringUtils.isBlank(htmlPath)) {
					String contextPath = request.getContextPath();
					htmlPath = request.getRequestURI();
					if(StringUtils.isNotBlank(contextPath) && !contextPath.equals("/")) {
						htmlPath = htmlPath.replaceFirst(contextPath, "");
					}
					if(StringUtils.isNotBlank(prefixPath)) {
						htmlPath = htmlPath.replaceFirst(prefixPath, "");
					}
				}
				
				HtmlTemplate htmlTemplateEntity = htmlThemeEntity.getTemplates().get(htmlPath);
				if(htmlTemplateEntity != null) {
					VelocityResource resource = new VelocityResource(htmlTemplateEntity.getRealFilePath());
					resource.export(request, response);
					return;
				}else {
					log.error("未找到HTML主题：" + htmlTheme + "的页面模版：" + htmlPath);
				}
			}else {
				log.error("未找到HTML主题：" + htmlTheme);
			}
		}else {
			log.error("无法获取HTML主题");
		}

	}

}
